<script lang="ts" setup>
import type { FieldRule, FormInstance } from '@arco-design/web-vue'
import type { WafListItem } from '@/apis/model/waf'
import type { CloudFilterBarState } from '@/components/filter-bar/types'
import type { IMatchingGroup } from '@/components/MatchingRule/types'
import { Message } from '@arco-design/web-vue'
import { omit } from 'lodash-es'
import { v4 as uuidV4 } from 'uuid'
// import {
//   addApiWafApi,
//   getApiWafGetApi,
//   getApiWafQueryApi,
//   updateApiWafApi,
// } from '@/apis/modules/waf'
import {
  addCdnNodeWafApi,
  getCdnNodeWafIdApi,
  getCdnNodeWafsApi,
  updateCdnNodeWafApi,
} from '@/apis/modules/cdn'
// import {
//   addSwitcherApi,
//   getSwitcherListApi,
//   updateCdnNodeWafApi,
// } from '@/apis/modules/switch'
import { getFieldValue } from '@/components/MatchingRule/utils'
import {
  A_EXECUTION_PRIORITY,
  A_EXECUTION_TYPE,
  priorityOptions,
} from '@/constants/cdn-node'

interface IProps {
  visible: boolean
  record?: any
}
const props = withDefaults(defineProps<IProps>(), {
  visible: false,
})
const emits = defineEmits<IEmits>()
interface IEmits {
  (e: 'update:visible', value: boolean): void
  (e: 'refresh'): void
}
const title = computed(() => (props?.record?.id ? '编辑规则' : '创建规则'))
const formRef = ref<FormInstance>()
const matchingView = ref()
const formData = ref({
  name: '',
  action: undefined,
  order: undefined,
  priority: undefined,
  scope: 3,
  module: 1,
  module_config: {},
  response_page: {
    type: 1,
    code: 403,
    body: '',
  },
})
const formRules = computed<{ [key: string]: FieldRule[] }>(() => {
  return {
    'name': [
      {
        required: true,
        message: '请输入规则名称',
      },
    ],
    'action': [
      {
        required: true,
        message: '请选择执行动作',
      },
    ],
    'order': [
      {
        required: true,
        message: '请选择执行优先级',
      },
    ],
    'priority': [
      {
        required: true,
        message: '请选择自定义规则',
      },
    ],
    'response_page.body': [{ required: true, message: '请输入响应内容' }],
    'response_page.code': [
      { required: true, message: '请输入响应代码' },
      {
        validator: (value, callback) => {
          if (!/^4\d{2}$/.test(value)) {
            callback('输入 4XX 状态代码')
          } else {
            callback()
          }
        },
      },
    ],
  }
})
const ruleGroups = ref<IMatchingGroup[]>([
  {
    uuid: uuidV4(),
    rules: [
      {
        uuid: uuidV4(),
        field: '',
        operator: '',
        value: '',
        custom_field: '',
      },
    ],
  },
])

function setDefaultType(val: number) {
  if (val === A_RESPONSE_TYPE.DEFAULT) {
    formData.value.response_page.code = 403
    formData.value.response_page.type = 1
  }
}
function setDefaultCode(val: number) {
  if (val === 1)
    formData.value.response_page.code = 403
}

const params = ref<CloudFilterBarState>({
  order: 'asc',
  // sort: 'created_at',
  sort: 'priority',
  scope: 3,
  module: 1,
  id: undefined,
})
const list = ref<WafListItem[]>([])
const filterList = ref<WafListItem[]>([])
const { run, pagination } = useListRequest(getCdnNodeWafsApi, {
  params,
  immediate: false,
  async afterFn(res) {
    await nextTick()
    list.value = res || []
    if (!list.value.length)
      return
    filterList.value = res.filter(item => item.id !== props?.record?.id)
  },
})
pagination.value.pageSize = 500
const prePriority = ref(0)
function handleChange(val) {
  if (val === 2) {
    if (prePriority.value === list.value[0].priority) {
      formData.value.priority = String(Number(prePriority.value) + 1)
    } else if (
      prePriority.value === list.value[list.value.length - 1].priority
    ) {
      formData.value.priority = String(Number(prePriority.value) - 1)
    }
  }
}
const { request } = useRequest(getCdnNodeWafIdApi, {
  success(res) {
    Object.assign(formData.value, res.info)
    prePriority.value = res.info.priority!
    if (!res.info?.response_page) {
      formData.value.response_page = {
        type: A_RESPONSE_TYPE.DEFAULT,
        code: 403,
        body: '',
      }
    }
    ruleGroups.value[0].rules = res.info.conditions.map((item) => {
      return {
        uuid: uuidV4(),
        value:
          getFieldValue(item)!.count > 1 ? item.value : item.value.toString(),
        ...item,
      }
    })
    // 转化响应代码为数字类型
    if (formData.value.response_page?.code) {
      formData.value.response_page.code = Number(
        formData.value.response_page.code,
      )
    }

    if (list.value.length) {
      if (list.value.length === 1)
        return (formData.value.order = formData.value.priority)

      const priorityArr = list.value.map((item: WafListItem) => item.priority!)
      const min = Math.min(...priorityArr)
      const max = Math.max(...priorityArr)
      switch (+formData.value.priority!) {
        case min:
          formData.value.order = A_EXECUTION_PRIORITY.FIRST
          break
        case max:
          formData.value.order = A_EXECUTION_PRIORITY.LAST
          break
        default:
          formData.value.order = A_EXECUTION_PRIORITY.CUSTOM
      }
    } else {
      formData.value.order = formData.value.priority
    }
    if (formData.value.order === A_EXECUTION_PRIORITY.CUSTOM) {
      formData.value.priority = String(Number(formData.value.priority) + 1)
    } else {
      formData.value.priority = formData.value.priority!
    }
  },
})
const getOption = computed(() => {
  if (props.record?.id) {
    return list.value.length > 2 ? priorityOptions : priorityOptions.slice(0, 2)
  } else {
    return list.value.length > 1 ? priorityOptions : priorityOptions.slice(0, 2)
  }
})
async function handleBeforeOpen() {
  await run()
  if (props.record)
    request({ id: props.record?.id })
}
async function handleBeforeClose() {
  await formRef.value?.resetFields()
  matchingView.value?.reset()
  emits('update:visible', false)
  formData.value.response_page = {
    type: 1,
    code: 403,
    body: '',
  }
  formData.value.priority = undefined
  formData.value.order = undefined
  formData.value.id = undefined
  formData.value.created_at = undefined
}
const saveLoading = ref(false)
async function handleSubmit() {
  const error = await formRef.value?.validate()
  const error1 = await matchingView.value.validate()
  if (error || !error1)
    return false
  saveLoading.value = true
  const data: any = {
    ...omit(formData.value, 'priority'),
    conditions: ruleGroups.value[0].rules.map((item) => {
      return {
        ...item,
        value: !Array.isArray(item.value)
          ? item.value
            ? [item.value]
            : []
          : item.value.filter(Boolean),
      }
    }),

    id: props.record ? props.record?.id : undefined,
  }
  if (
    formData.value.action === A_EXECUTION_TYPE.OBSERVE
    || formData.value.action === A_EXECUTION_TYPE.JS
    || formData.value.action === A_EXECUTION_TYPE.INTERACTIVE
  ) {
    data.response_page = null
  }
  if (formData.value?.order === A_EXECUTION_PRIORITY.FIRST) {
    data.priority = 1
  } else if (formData.value?.order === A_EXECUTION_PRIORITY.LAST) {
    data.priority = 0
  } else {
    data.priority = formData?.value?.priority
  }
  const api_path = props.record ? updateCdnNodeWafApi : addCdnNodeWafApi
  api_path(data)
    .then(() => {
      Message.success('操作成功')
      emits('update:visible', false)
      emits('refresh')
    })
    .finally(() => (saveLoading.value = false))
}
</script>

<template>
  <a-drawer
    :visible="visible"
    :title="title"
    ok-text="保存"
    width="1000px"
    :loading="saveLoading"
    @ok="handleSubmit"
    @open="handleBeforeOpen"
    @close="handleBeforeClose"
    @cancel="emits('update:visible', false)"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      layout="vertical"
    >
      <a-form-item
        field="name"
        label="规则名称"
        asterisk-position="end"
        required
      >
        <a-input
          v-model="formData.name"
          :max-length="20"
          class="!w-110"
          placeholder="请输入规则名称"
        />
      </a-form-item>
      <a-form-item
        label="如果请求匹配以下规则"
        asterisk-position="end"
        required
        class="rule-help-item"
      >
        <matching-rule-view
          ref="matchingView"
          v-model="ruleGroups"
          class="w-full"
        />
      </a-form-item>
      <a-form-item
        field="action"
        label="执行策略"
        asterisk-position="end"
        required
        hide-asterisk
      >
        <template #label>
          <span class="text-xs/5">则执行</span>
        </template>
        <a-select
          v-model="formData.action"
          placeholder="请选择执行策略"
          class="!w-110"
          :options="wafCustomOptions"
          @change="setDefaultType"
        />
      </a-form-item>

      <section
        v-if="formData.action === 1"
        class="mb-6"
      >
        <a-form-item
          label="响应类型"
          required
          hide-asterisk
          field="response_page.type"
        >
          <a-select
            v-model="formData.response_page.type"
            class="!w-110"
            placeholder="请选择响应类型"
            @change="setDefaultCode"
          >
            <a-option
              v-for="item in RESPONSE_TYPE_LIST"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </a-select>
        </a-form-item>
        <a-form-item
          label="响应代码"
          required
          hide-asterisk
          field="response_page.code"
        >
          <a-input-number
            v-model="formData.response_page.code"
            hide-button
            :precision="0"
            :max-length="30"
            class="!w-110"
            :disabled="formData.response_page.type === 1"
            placeholder="请输入响应代码"
          />
        </a-form-item>
        <a-form-item
          v-if="formData.response_page.type !== 1"
          label="响应内容"
          required
          hide-asterisk
          class="!mb-2"
          field="response_page.body"
        >
          <a-textarea
            v-model="formData.response_page.body"
            :max-length="10000"
            show-word-limit
            :auto-size="{ minRows: 5, maxRows: 5 }"
            class="h-fit w-full"
            :placeholder="`请输入显示页面的${getOptionsLabel(
              RESPONSE_TYPE_LIST,
              formData.response_page.type,
            )}`"
          />
        </a-form-item>
        <section
          v-if="formData.response_page.type !== 1"
          class="w-fit flex cursor-pointer items-center gap-x-6px"
          @click="previewWithNewPage(formData.response_page.body)"
        >
          <a-link :hoverable="false">
            预览效果
          </a-link>
          <!-- <i-icons-new-page /> -->
        </section>
      </section>
      <a-form-item
        v-if="filterList.length > 0"
        field="order"
        label="执行优先级"
        asterisk-position="end"
        required
      >
        <section class="flex flex-col">
          <a-select
            v-model="formData.order"
            placeholder="请选择执行优先级"
            class="!w-110"
            :options="getOption"
            @change="handleChange"
          />
          <a-form-item
            v-if="formData.order === A_EXECUTION_PRIORITY.CUSTOM"
            field="priority"
            asterisk-position="end"
            class="mt-2 !mb-0"
            required
            hide-label
          >
            <a-select
              v-model="formData.priority"
              class="w-[336px]"
              placeholder="优先触发创建的规则，再触发选择的规则"
            >
              <a-option
                v-for="item in props?.record?.id ? filterList : list"
                :key="item.id"
                :label="item.name"
                :value="item.priority"
              />
            </a-select>
          </a-form-item>
          <span
            v-if="formData.order === A_EXECUTION_PRIORITY.CUSTOM"
            class="text-xs/5 text-[#86909C]"
          >在此规则前执行。</span>
        </section>
      </a-form-item>
    </a-form>
  </a-drawer>
</template>

<style lang="less" scoped>
:deep(.arco-input-disabled) {
  border-color: #e5e6eb !important;
}
</style>
